package com.hnevc.androidui10;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class WeatherActivity extends AppCompatActivity {
    Button mBtnSh,mBtnBj, mBtnGz;
    TextView mTvWeather;

 List<Weather> weatherList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        initData();
        initView();
        initEVent();
    }

    private void initView() {
        mBtnBj=findViewById(R.id.btn_bj);
        mBtnSh=findViewById(R.id.btn_sh);
        mBtnGz =findViewById(R.id.btn_gz);
        mTvWeather =findViewById(R.id.tv_weather);
    }

    private void initEVent() {
    mBtnSh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Weather w =weatherList.get(0);
            mTvWeather.setText(w.getWeather());
        }
    });


    }

    private  void  initData(){
        weatherList =new ArrayList<>();
        try {
        InputStream in = this.getResources().openRawResource(R.raw.weather2);

            byte[] bytes=new byte[in.available()];
            in.read(bytes);
            String temp =new String(bytes);

        JSONArray jsonArray =new JSONArray(temp);
        for (int i=0;i< jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String temp1 =jsonObject.getString("temp");
            String weather =jsonObject.getString("weather");
            String wind =jsonObject.getString("wind");
            String name =jsonObject.getString("name");
            String pm =jsonObject.getString("pm");

            Weather w =new Weather();
            w.setName(name);
            w.setPm(pm);
            w.setTemp(temp1);
            w.setWeather(weather);
            w.setWind(wind);
            weatherList.add(w);
        }

    }catch(Exception e){
        }
    }
}
